<?php
/**
 * (logic) 销量预估周期性更新
 */
namespace App\Logic\SsBasic;
use App\Models\SsBasic\AreaClassifyEstimate;
use App\Models\SsBasic\AreaSkuEstimate;
use App\Models\SsBasic\EstimateLog;
use Illuminate\Support\Facades\DB;
class InitEstimate
{
    /** 站点品类预估和站点品类sku预估 (ss:estimate)
     * 设定：每月1日
     */
    public static function exe(){
        try{
            $day = date('j');
            if($day != 1)die('不符合更新条件');

            //站点品类预估
            AreaClassifyEstimate::query()->orderBy('id')
                ->chunk(500, function ($ace){
                    DB::beginTransaction();
                    foreach ($ace as $_ace){
                        $beforeData = json_encode($_ace->toarray()); //旧数据

                        for($i = 0;$i < AreaSkuEstimate::ESTIMATE_NUM;$i++){
                            if($i == (AreaSkuEstimate::ESTIMATE_NUM - 1)){
                                $_ace->{'estimate_num'.$i} = 0;
                            }else{
                                $_ace->{'estimate_num'.$i} = $_ace->{'estimate_num'.($i+1)};
                            }
                        }
                        $_ace->save();

                        //预估日志
                        $afterData = json_encode($_ace->toarray()); //新数据
                        $logData = [];
                        $logData['area_id'] = $_ace->area_id;
                        $logData['country_id'] = 0;
                        $logData['classify_id'] = $_ace->classify_id;
                        EstimateLog::addLog($beforeData, $afterData, EstimateLog::TYPE_AREA_ESTIMATE_CLASSIFY, $logData);
                    }
                    DB::commit();
                });
            sleep(5);

            //站点sku预估
            AreaSkuEstimate::query()->orderBy('id')
                ->chunk(500, function ($ase){
                    DB::beginTransaction();
                    foreach ($ase as $_ase){
                        //$beforeData = json_encode($_ase->toarray()); //旧数据

                        for($i = 0;$i < AreaSkuEstimate::ESTIMATE_NUM;$i++){
                            if($i == (AreaSkuEstimate::ESTIMATE_NUM - 1)){
                                $_ase->{'estimate_num'.$i} = 0;
                            }else{
                                $_ase->{'estimate_num'.$i} = $_ase->{'estimate_num'.($i+1)};
                            }
                        }
                        $_ase->save();

                        ////预估日志
                        //$afterData = json_encode($_ase->toarray()); //新数据
                        //EstimateLog::addLog($beforeData, $afterData, EstimateLog::TYPE_AREA_ESTIMATE_SKU);
                    }
                    DB::commit();
                });
        }catch (\Exception $e){
            report($e);
        }

        dd('finish!');
    }

}
